import 'dart:async';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
import 'SPConstants.dart';
//使用方法
// SPUtils.save("LicenseModel", action.payload);
// SPUtils.get("LicenseModel").then((val) {
//   print(val);
//
// });

//统一存储数据工具
class SPUtils {
  //单个字符保存
  static save(var key, var data) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (data is String) {
      prefs.setString(key, data);
    } else if (data is int) {
      prefs.setInt(key, data);
    } else if (data is double) {
      prefs.setDouble(key, data);
    } else if (data is bool) {
      prefs.setBool(key, data);
    }
  }
 //单个字符读取
  static Future<Object> get(var key) async {
    var value;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    value = prefs.get(key);
    return await value;
  }

  //获取数据
  static Future getData(String key) async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    final jsonStr = pref.getString(key);
    // print(jsonStr);
    if (jsonStr != null && jsonStr.length > 0) {
      Map json = jsonDecode(jsonStr);
      return json;
    }
    return null;
  }

  //保存数据
  static Future saveData(String key,var data) async {
    //保存data
    SharedPreferences pref= await SharedPreferences.getInstance();
    //将data转换成json
    var str = json.encode(data);
    pref.setString(key, str);
  }

  //移除数据
  static Future removeData(String key) async{
    //移除已存数据
    SharedPreferences pref= await SharedPreferences.getInstance();
    pref.remove(key);
  }
}
